package base.Chapter00_Structures.C05_Queue;

/**
 * 循环队列
 * <p>
 * 属性列表
 * 1，capacity
 * 2，head
 * 3，tail
 * 4，container【】
 * <p>
 * 功能列表
 * 1，入队
 * 判断是否已满
 * head
 * (tail+1)%capcacity=head
 * 2，出队
 * 判断是否为空： head==tail
 */
public class CircularQueue {

    private final int capacity;
    private int head;
    private int tail;
    private final String[] container;

    public CircularQueue(int capacity) throws Exception {
        if (capacity < 0) {
            throw new Exception("Capacity is illegal!");
        }
        this.capacity = capacity;
        container = new String[capacity];
        this.head = 0;
        this.tail = 0;
    }

    public boolean enqueue(String e) {
        //Check: isFull
        if ((tail + 1) % capacity == head) {
            return false;
        }
        /*int index = tail+1==capacity?0:tail;
        container[index]=e;
        tail++;*/

        container[tail] = e;
        tail = (tail + 1) % capacity;
        return true;
    }

    public String dequeue() {
        //Check: isEmpty
        if (head == tail) {
            return null;
        }

        return container[head++];
    }
}
